import React, { useState, useMemo, useEffect } from 'react';
import { InputNumber, Radio, Button, Tooltip, message } from 'antd';
import './App.css';

const DIMENSIONS = {
  VALUE: { 
    color: '#FF6B6B', 
    label: 'Value',
    description: 'Current valuation metrics and price relative to fundamentals'
  },
  FUTURE: { 
    color: '#4ECDC4', 
    label: 'Future',
    description: 'Growth prospects and expected performance indicators'
  },
  PAST: { 
    color: '#45B7D1', 
    label: 'Past',
    description: 'Historical performance and track record consistency'
  },
  HEALTH: { 
    color: '#96CEB4', 
    label: 'Health',
    description: 'Financial stability and operational efficiency metrics'
  },
  DIVIDEND: { 
    color: '#FFEAA7', 
    label: 'Dividend',
    description: 'Dividend sustainability and income generation potential'
  }
};

const dimensionOrder = ['VALUE', 'FUTURE', 'PAST', 'HEALTH', 'DIVIDEND'];

const SnowflakeChart = ({ type = 'COMPANY', data, onSectorClick, getTooltipContent }) => {
  const svgSize = 300;
  const centerX = svgSize / 2;
  const centerY = svgSize / 2;
  const maxRadius = 100;
  
  const generatePoints = (values) => {
    const angleStep = (Math.PI * 2) / 5;
    const startAngle = -Math.PI / 2;
    
    return values.map((value, index) => {
      const angle = startAngle + index * angleStep;
      const radius = (value / 7) * maxRadius;
      return {
        x: centerX + Math.cos(angle) * radius,
        y: centerY + Math.sin(angle) * radius,
        angle: angle * 180 / Math.PI
      };
    });
  };

  const points = useMemo(() => {
    return generatePoints(dimensionOrder.map(dim => data[dim]?.score || 0));
  }, [data]);

  const getPolygonPath = () => {
    return points.map(p => `${p.x},${p.y}`).join(' ');
  };

  const getSectorPath = (index) => {
    const angleStep = (Math.PI * 2) / 5;
    const startAngle = -Math.PI / 2;
    const currentAngle = startAngle + index * angleStep;
    const nextAngle = startAngle + ((index + 1) % 5) * angleStep;
    
    const outerRadius = (data[dimensionOrder[index]]?.score || 0) / 7 * maxRadius;
    
    const x1 = centerX + Math.cos(currentAngle) * 0;
    const y1 = centerY + Math.sin(currentAngle) * 0;
    const x2 = centerX + Math.cos(currentAngle) * outerRadius;
    const y2 = centerY + Math.sin(currentAngle) * outerRadius;
    const x3 = centerX + Math.cos(nextAngle) * outerRadius;
    const y3 = centerY + Math.sin(nextAngle) * outerRadius;
    const x4 = centerX + Math.cos(nextAngle) * 0;
    const y4 = centerY + Math.sin(nextAngle) * 0;
    
    return `M ${x1} ${y1} L ${x2} ${y2} L ${x3} ${y3} L ${x4} ${y4} Z`;
  };

  const handleSectorClick = (index) => {
    if (type === 'COMPANY' && onSectorClick) {
      onSectorClick(index);
    }
  };

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <svg width={svgSize} height={svgSize} className="snowflake-chart">
        {dimensionOrder.map((dim, index) => {
          const isHighlighted = type === 'TOC' && data.highlightedDimension === dim;
          const dimension = DIMENSIONS[dim];
          const score = data[dim]?.score || 0;
          
          return (
            <g key={dim}>
              {/* 主扇形区域 */}
              <path
                d={getSectorPath(index)}
                fill={dimension.color}
                fillOpacity={type === 'TOC' && data.highlightedDimension === dim ? 1 : 0.7}
                stroke="#fff"
                strokeWidth="2"
                className={`sector ${type === 'COMPANY' ? 'clickable' : ''}`}
                onClick={() => handleSectorClick(index)}
                style={{
                  transition: 'all 0.3s ease',
                  cursor: type === 'COMPANY' ? 'pointer' : 'default',
                  filter: isHighlighted ? 'brightness(1.3)' : 'none'
                }}
              />
              
              <text
                x={centerX + Math.cos(((-Math.PI / 2) + index * (Math.PI * 2) / 5)) * (maxRadius + 20)}
                y={centerY + Math.sin(((-Math.PI / 2) + index * (Math.PI * 2) / 5)) * (maxRadius + 20)}
                textAnchor="middle"
                dominantBaseline="middle"
                fontSize="12"
                fill="#666"
              >
                {dimension.label}
              </text>
            </g>
          );
        })}
        
        <polygon
          points={getPolygonPath()}
          fill="none"
          stroke="#333"
          strokeWidth="2"
          strokeDasharray="5,5"
        />
        
        {[0, 1, 2, 3, 4, 5, 6, 7].map(level => (
          <circle
            key={level}
            cx={centerX}
            cy={centerY}
            r={level === 0 ? 0 : (level / 7) * maxRadius}
            fill="none"
            stroke="#ddd"
            strokeWidth="1"
            strokeDasharray="2,2"
          />
        ))}
      </svg>
      
      {type === 'COMPANY' && (
        <svg 
          width={svgSize} 
          height={svgSize} 
          style={{ position: 'absolute', top: 0, left: 0, pointerEvents: 'none' }}
        >
          {dimensionOrder.map((dim, index) => {
            const angleStep = (Math.PI * 2) / 5;
            const startAngle = -Math.PI / 2;
            const currentAngle = startAngle + index * angleStep;
            const nextAngle = startAngle + ((index + 1) % 5) * angleStep;
            const baseRadius = (data[dim]?.score || 0) / 7 * maxRadius;
            
            const x1 = centerX + Math.cos(currentAngle) * 0;
            const y1 = centerY + Math.sin(currentAngle) * 0;
            const x2 = centerX + Math.cos(currentAngle) * baseRadius;
            const y2 = centerY + Math.sin(currentAngle) * baseRadius;
            const x3 = centerX + Math.cos(nextAngle) * baseRadius;
            const y3 = centerY + Math.sin(nextAngle) * baseRadius;
            const x4 = centerX + Math.cos(nextAngle) * 0;
            const y4 = centerY + Math.sin(nextAngle) * 0;
            
            const sectorPath = `M ${x1} ${y1} L ${x2} ${y2} L ${x3} ${y3} L ${x4} ${y4} Z`;
            
            return (
              <g key={`overlay-${dim}`}>
                <Tooltip
                  title={getTooltipContent(dim)}
                  placement="top"
                  mouseEnterDelay={0}
                  mouseLeaveDelay={0}
                  overlayStyle={{ pointerEvents: 'none' }}
                >
                  <path
                    d={sectorPath}
                    fill="transparent"
                    stroke="none"
                    style={{
                      pointerEvents: 'auto',
                      cursor: 'pointer'
                    }}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleSectorClick(index);
                    }}
                  />
                </Tooltip>
              </g>
            );
          })}
        </svg>
      )}
    </div>
  );
};

function App() {
  const [type, setType] = useState('COMPANY');
  const [highlightedDimension, setHighlightedDimension] = useState(null);
  
  const initialData = {
    VALUE: { score: 5, section: [true, true, false, true, true, false] },
    FUTURE: { score: 4, section: [true, false, true, true, false, false] },
    PAST: { score: 6, section: [true, true, true, true, false, true] },
    HEALTH: { score: 3, section: [false, true, false, true, true, false] },
    DIVIDEND: { score: 4, section: [true, true, false, false, true, false] }
  };
  
  const [data, setData] = useState(initialData);

  const handleScoreChange = (dimension, value) => {
    setData(prev => ({
      ...prev,
      [dimension]: { ...prev[dimension], score: value }
    }));
  };

  const handleRadioChange = (e) => {
    const selectedDimension = e.target.value;
    setHighlightedDimension(selectedDimension);
    setType('TOC');
    setData(prev => ({
      ...prev,
      highlightedDimension: selectedDimension
    }));
  };

  const handleReset = () => {
    setData(initialData);
    setHighlightedDimension(null);
    setType('COMPANY');
  };

  const handleSectorClick = (index) => {
    const dimension = dimensionOrder[index];
    const dimensionData = data[dimension];
    const dimensionInfo = DIMENSIONS[dimension];
    
    const content = `
      ${dimensionInfo.label} Analysis
      Score: ${dimensionData.score}/7
      Description: ${dimensionInfo.description}
    `;
    
    message.info({
      content: (
        <div>
          <strong>{dimensionInfo.label} Sector Selected</strong>
          <div style={{ marginTop: '4px', fontSize: '12px' }}>
            Score: {dimensionData.score}/7 | Index: {index}
          </div>
        </div>
      ),
      duration: 3
    });
  };

  const getTooltipContent = (dimension) => {
    const dimensionData = data[dimension];
    const dimensionInfo = DIMENSIONS[dimension];
    if (!dimensionData || !dimensionInfo) return '';
    
    return (
      <div style={{ minWidth: '200px', padding: '4px' }}>
        <div style={{ 
          fontSize: '14px', 
          fontWeight: 'bold', 
          marginBottom: '8px',
          color: dimensionInfo.color 
        }}>
          {dimensionInfo.label} Dimension
        </div>
        <div style={{ 
          fontSize: '12px', 
          color: '#666', 
          marginBottom: '8px',
          fontStyle: 'italic'
        }}>
          {dimensionInfo.description}
        </div>
        <div style={{ fontSize: '12px', marginBottom: '6px' }}>
          <strong>Score:</strong> <span style={{ fontSize: '14px', fontWeight: 'bold' }}>{dimensionData.score}/7</span>
        </div>
        <div style={{ fontSize: '12px', marginBottom: '6px' }}>
          <strong>Sub-scores:</strong>
        </div>
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(3, 1fr)', 
          gap: '4px',
          marginTop: '4px',
          marginBottom: '8px'
        }}>
          {dimensionData.section.map((val, idx) => (
            <div
              key={idx}
              style={{
                width: '16px',
                height: '16px',
                backgroundColor: val ? dimensionInfo.color : '#f0f0f0',
                border: `1px solid ${val ? dimensionInfo.color : '#ccc'}`,
                borderRadius: '2px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '10px',
                color: val ? '#fff' : '#999'
              }}
            >
              {val ? '✓' : ''}
            </div>
          ))}
        </div>
        <div style={{ 
          fontSize: '11px', 
          color: '#999',
          borderTop: '1px solid #eee',
          paddingTop: '6px'
        }}>
          Click to see detailed analysis
        </div>
      </div>
    );
  };

  return (
    <div className="App">
      <div className="container">
        <h1>Snowflake Chart</h1>
        
        <div className="type-selector">
          <span>Type: </span>
          <Radio.Group value={type} onChange={e => setType(e.target.value)}>
            <Radio.Button value="COMPANY">Company</Radio.Button>
            <Radio.Button value="TOC">TOC</Radio.Button>
          </Radio.Group>
        </div>

        {type === 'TOC' && (
          <div className="dimension-selector">
            <span>Highlight Dimension: </span>
            <Radio.Group value={highlightedDimension} onChange={handleRadioChange}>
              {Object.entries(DIMENSIONS).map(([key, dim]) => (
                <Radio key={key} value={key}>{dim.label}</Radio>
              ))}
            </Radio.Group>
          </div>
        )}

        <div className="chart-container">
          <SnowflakeChart 
            type={type} 
            data={{...data, highlightedDimension}} 
            onSectorClick={handleSectorClick}
            getTooltipContent={getTooltipContent}
          />
        </div>

        <div className="controls">
          <div className="score-controls">
            {dimensionOrder.map(dimension => (
              <div key={dimension} className="control-item">
                <label style={{ color: DIMENSIONS[dimension].color }}>
                  {DIMENSIONS[dimension].label}:
                </label>
                <InputNumber
                  min={0}
                  max={7}
                  value={data[dimension]?.score || 0}
                  onChange={value => handleScoreChange(dimension, value)}
                  style={{ width: '80px' }}
                />
              </div>
            ))}
          </div>
          
          <Button onClick={handleReset} style={{ marginTop: '20px' }}>
            Reset
          </Button>
        </div>
      </div>
    </div>
  );
}

export default App;
